
//--------------------------------------------------------------------
//     此代码由T4模板自动生成
//	   生成时间 2021-09-07 19:42:15 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TianYu.CMS.Domain.DomainModel;
using TianYu.CMS.Domain.ViewModel.Request;
using TianYu.CMS.Infrastructure.Enums;
using TianYu.CMS.Service;
using TianYu.Core.Common;
using TianYu.Core.Common.BaseViewModel;

namespace TianYu.CMS.WebMvc.Areas.Admin.Controllers
{
    public class AdvPositionController : BaseController
    {
        private IAdvPositionService _advPositionService;
        public AdvPositionController(IAdvPositionService advPositionService)
        {
            this._advPositionService = advPositionService;
        }



        public IActionResult Index()
        {
            return View();
        }
        public IActionResult AddEdit(string guid)
        {
            var model = new AdvPosition();
            if (!string.IsNullOrWhiteSpace(guid))
            {
                model = _advPositionService.FindById(guid);
            }

            return View(model);
        }




        public async Task<AjaxResult<List<AdvPosition>>> GetList([FromQuery] BaseRequest requestModel)
        {
            var filter = Expressionable.Create<AdvPosition>()
                .AndIF(!requestModel.KeyWords.IsNullOrWhiteSpace(), o => o.Name.Contains(requestModel.KeyWords))
                .ToExpression();

            var list = await _advPositionService.QueryAsync(filter, o => o.Id, OrderByType.Desc);
             
            return list.ToViewModel();
        }
        public async Task<AjaxResult<bool>> Save(AdvPosition requestModel)
        {
            if (requestModel.Name.IsNullOrWhiteSpace())
            {
                return AjaxResult<bool>.Fail("广告位名称不能为空");
            }
            var isExist = await _advPositionService.AnyAsync(o => o.Id != requestModel.Id && o.Name == requestModel.Name);
            if (isExist)
            {
                return AjaxResult<bool>.Fail($"广告位名称[{requestModel.Name}]已存在不能重复添加");
            }
            var isCodeExist = await _advPositionService.AnyAsync(o => o.Id != requestModel.Id && o.Code == requestModel.Code);
            if (isCodeExist)
            {
                return AjaxResult<bool>.Fail($"广告位编码[{requestModel.Code}]已存在不能重复添加");
            }
            var res = false;
            if (requestModel.Id > 0)
            {
                res = await _advPositionService.UpdateAsync(requestModel);
            }
            else
            {
                res = await _advPositionService.InsertAsync(requestModel) > 0;
            }
            return res ? AjaxResult<bool>.Success() : AjaxResult<bool>.Fail("保存失败");
        }
    }
}

